package aeemqx

import (
	"context"
	"devops-super/internal/consts"
	"devops-super/internal/consts/cacheConsts"
	"devops-super/internal/model/mymodel"
	"devops-super/internal/service"
	"devops-super/pb"
	"encoding/json"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/golang/protobuf/proto"
	"strings"
	"time"
)

func (s *sAeemqx) SaveDeviceTmpInfo(ctx context.Context, deviceNo string, aetype string, data []byte, ops *mymodel.EmqxPublishOps) (err error) {
	if ops != nil && ops.Retained && ops.ConfigType != "" && deviceNo != "" {
		cacheKey := cacheConsts.GetCacheAeDeviceTmpConfKey(deviceNo, aetype)
		var m = mymodel.DeviceTmpMqttMsgInfo{
			DeviceNo: deviceNo,
			Aetype:   aetype,
			Data:     data,
			Ops:      ops,
		}
		cacheData, err := json.Marshal(m)
		if err != nil {
			return err
		}
		err = service.GetCacheInstance().Set(ctx, cacheKey, string(cacheData), 0)
	}
	return
}

// RecoverDeviceTmpInfo 当设备重新在线时，需要将配置发给设备，保证设备配置是最新的
func (s *sAeemqx) RecoverDeviceTmpInfo(ctx context.Context, deviceNo string) (err error) {
	//fix
	if strings.HasPrefix(deviceNo, "web") || strings.HasPrefix(deviceNo, "app") ||
		strings.HasPrefix(deviceNo, "aes") || strings.HasPrefix(deviceNo, "server") {
		return
	}
	allConfigs := [...]string{
		consts.DeviceConfTypeParamConfig,
		consts.DeviceConfTypeLevelConfig2,
		consts.DeviceConfTypeTimingConfig,
		consts.DeviceConfTypeFirConfig,
		consts.DeviceConfTypeAeFftConfig,
		consts.DeviceConfTypeViMeasureConfig,
	}
	for _, confKey := range allConfigs {
		cKey1 := cacheConsts.GetCacheAeDeviceTmpConfKey(deviceNo, confKey)
		result1, err := service.GetCacheInstance().Get(ctx, cKey1)
		if err != nil {
			break
		}
		if !result1.IsEmpty() {
			var data1 *mymodel.DeviceTmpMqttMsgInfo
			err := json.Unmarshal([]byte(result1.String()), &data1)
			if err == nil && data1.DeviceNo != "" {
				go func(data1 *mymodel.DeviceTmpMqttMsgInfo) {
					if data1 == nil {
						return
					}
					//加点延迟 以免设备还没订阅就发送了。
					time.Sleep(time.Millisecond * time.Duration(666)) //666毫秒
					err := service.Aeemqx().CommonAePublish(ctx, data1.DeviceNo, data1.Aetype, data1.Data, data1.Ops)
					if err != nil {
						return
					}
				}(data1)
			}
			// 发完之后得清除掉 避免一直发
			_, err = service.GetCacheInstance().Remove(ctx, cKey1)
		}
	}
	return
}

func (s *sAeemqx) SendServerInfoToDevice(ctx context.Context, deviceNo string) (err error) {
	serverInfo := &pb.ServerInfo{
		ServerTime: uint32(gtime.Now().Unix()),
	}
	aeMsg := &pb.SensorMessage{
		NodeId:      deviceNo,
		UnixTime:    uint32(gtime.Now().Unix()),
		Microsecond: int32(gtime.Now().Microsecond()),
		Msg:         &pb.SensorMessage_ServerInfo{ServerInfo: serverInfo},
	}
	pData, err := proto.Marshal(aeMsg)
	if err != nil {
		return err
	}
	err = service.Aeemqx().CommonAePublish(ctx, deviceNo, consts.MqttServerInfo, pData, &mymodel.EmqxPublishOps{Retained: false})
	return err
}
